package com.sunnada.demo.log.service.impl;

import com.sunnada.demo.log.LogCommon;
import com.sunnada.demo.log.bean.TrackLog;
import com.sunnada.demo.log.dao.TrackLogRepository;
import com.sunnada.demo.log.service.TrackLogService;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.thymeleaf.util.StringUtils;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.sound.midi.Track;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.regex.Pattern;

/**
 * @program: mybatisproject2
 * @description: 操作日志实现
 *            有两种方法实现：1、是JPA 2、是mongoTemplate
 * @author: 李瑞益
 * @create: 2018-10-28 14:26
 **/
@Service
public class TrackLogServiceImpl implements TrackLogService {

    @Autowired
    private TrackLogRepository trackLogRepository;

    @Autowired
    private MongoTemplate mongoTemplate;

//    @Autowired
//    private DogR dogR;
//    @Autowired
//    private TrackSpecification trackSpecification;
//private TestRepositiory testRepository;


    @Override
    public List<TrackLog> findAll() {
//        return trackLogRepository.findAll();
        return mongoTemplate.findAll(TrackLog.class);
    }

    @Override
    public TrackLog findOne(String id) {
        //创建匹配器
        ExampleMatcher matcher = ExampleMatcher.matching()
                .withMatcher("id", ExampleMatcher.GenericPropertyMatchers.contains());
//                .withIgnorePaths("id");
        //创建实例
        TrackLog t = new TrackLog();
        t.setId(id);
        Example<TrackLog> example = Example.of(t, matcher);
        Optional<TrackLog> one = trackLogRepository.findOne(example);

        //mongoTemplate
        Query query = new Query(Criteria.where("id").is(id));
        TrackLog one1 = mongoTemplate.findOne(query, TrackLog.class);
        if (one.isPresent())
            return one.get();


        return one1;
    }

    @Override
    public void addTrackLog(TrackLog trackLog) {
        TrackLog save = trackLogRepository.save(trackLog);

    }

    /**
     * 使用的是mongodbRepository，exampleMathcher构造条件，没法范围查询
     * @param pageNumber
     * @param pageSize
     * @param userName
     * @param operationType
     * @return
     */
    @Override
    public Page<TrackLog> findByTime(int pageNumber, int pageSize, String userName, String operationType) {
        //使用JPA的方式
        //排序
        Sort sort = new Sort(Sort.Direction.DESC,"createTime");
        //分页对象
        Pageable pageRequest = PageRequest.of(pageNumber-1, pageSize,sort);

        //创建匹配器
        ExampleMatcher example = ExampleMatcher.matching()//构建对象
                .withMatcher("userName", ExampleMatcher.GenericPropertyMatchers.contains());//属性参数,contains(包含有的查询方式类似模糊查询）、startbigging(开始有）
        //范围匹配
//        Range<TrackLog> range = new Range<TrackLog>(new Date(),new Date());
        //条件，将查询的参数赋值到对应字段
        TrackLog trackLog = new TrackLog();
        if(!StringUtils.isEmpty(userName))
             trackLog.setUserName(userName);
        if(!StringUtils.isEmpty(operationType))
            //对象的精准查找不用设置匹配器
             trackLog.setOperationType(operationType);
        //创建查询实例
        Example<TrackLog> e = Example.of(trackLog, example);

        Page<TrackLog> all = trackLogRepository.findAll(e, pageRequest);//查询
        for(TrackLog log : all){
            log.setCreateTime(LogCommon.getBjTime(log.getCreateTime()));
        }
        return all;
    }

    /**
     * 使用的是mongodbTemplate方式
     * @param pageNumber
     * @param pageSize
     * @param trackLog
     * @param startTime
     * @param endTime
     * @return
     */
    @Override
    public Page<TrackLog> find(int pageNumber, int pageSize, TrackLog trackLog, String startTime, String endTime) {

        //排序：倒序
        Sort sort = new Sort(Sort.Direction.DESC,"createTime");
        //分页对象
        Pageable page = PageRequest.of(pageNumber-1,pageSize,sort);

        //封装对象
        Query query = new Query();
        //构建查询条件
//        if (!StringUtils.isEmpty(trackLog.getUserId())) {
//            query.addCriteria(Criteria.where("userId").regex(Pattern.compile(".*"+trackLog.getUserId()+".*")));
//        }
//        if (!StringUtils.isEmpty(trackLog.getUserName())) {
//            query.addCriteria(Criteria.where("userName").regex(Pattern.compile(".*"+trackLog.getUserName()+".*")));
//        }
//        if (!StringUtils.isEmpty(trackLog.getCompanyId())) {
//            query.addCriteria(Criteria.where("companyId").regex(Pattern.compile(".*"+trackLog.getCompanyId()+".*")));
//        }
//        if (!StringUtils.isEmpty(trackLog.getLogMessage())) {
//            query.addCriteria(Criteria.where("logMessage").regex(Pattern.compile(".*"+trackLog.getLogMessage()+".*")));
//        }
//        if (!StringUtils.isEmpty(trackLog.getOperationType())) {
//            query.addCriteria(Criteria.where("operationType").regex(Pattern.compile(".*"+trackLog.getOperationType()+".*")));
//        }
//        if (!StringUtils.isEmpty(trackLog.getEntityName())) {
//            query.addCriteria(Criteria.where("entityName").regex(Pattern.compile(".*"+trackLog.getEntityName()+".*")));
//        }
//        if (!StringUtils.isEmpty(trackLog.getClasDisplayName())) {
//            query.addCriteria(Criteria.where("classDiaplayName").regex(Pattern.compile(".*"+trackLog.getClasDisplayName()+".*")));
//        }
//        if (!StringUtils.isEmpty(trackLog.getUrl())) {
//            query.addCriteria(Criteria.where("url").regex(Pattern.compile(".*"+trackLog.getUrl()+".*")));
//        }
        //使用匹配器
        ExampleMatcher matcher = ExampleMatcher.matching()
                .withIgnoreNullValues()
                .withMatcher("userId",ExampleMatcher.GenericPropertyMatchers.contains())
                .withMatcher("userName",ExampleMatcher.GenericPropertyMatchers.contains())
                .withMatcher("companyId",ExampleMatcher.GenericPropertyMatchers.contains())
                .withMatcher("entityName",ExampleMatcher.GenericPropertyMatchers.contains())
                .withMatcher("operationType",ExampleMatcher.GenericPropertyMatchers.contains())
                .withMatcher("logMessage",ExampleMatcher.GenericPropertyMatchers.contains())
                .withMatcher("url",ExampleMatcher.GenericPropertyMatchers.caseSensitive())
//                .withMatcher("entityName",ExampleMatcher.GenericPropertyMatchers.contains())
                .withMatcher("_class",ExampleMatcher.GenericPropertyMatchers.contains())
                .withIgnorePaths("clasDisplayName")
                .withIgnorePaths("createTime")
                .withIgnorePaths("_id");

        Example<TrackLog> ex = Example.of(trackLog,matcher);
        query.addCriteria(Criteria.byExample(ex));
        //范围
        if (startTime != null || endTime != null) {
            Criteria criteria = new Criteria("createTime");
            if(!org.springframework.util.StringUtils.isEmpty(startTime)) {
                criteria.gt(startTime);
            }
            if (!org.springframework.util.StringUtils.isEmpty(endTime)) {
                criteria.lt(endTime);
            }
            query.addCriteria(criteria);
        }
        //页总数
        long count = mongoTemplate.count(query, TrackLog.class);
        //每页数据
        List<TrackLog> dogs = mongoTemplate.find(query.with(page), TrackLog.class);
        //封装成page对象
        Page<TrackLog> dogPage = new PageImpl<>(dogs,page,count);
        for(TrackLog log : dogPage){
            log.setCreateTime(LogCommon.getBjTime(log.getCreateTime()));
        }
        return dogPage;
    }

}
